<?php

namespace app\admin\controller;

use app\admin\model\Category;
use app\admin\model\Goods as GoodsM;
use think\Db;
use think\facade\Request;
use think\facade\Session;

class Goods extends Base
{
    public function initialize()
    {
        if (Session::get('username') == '') {
            $this->error("请先登录", 'base/login');
        }
    }

    function goodsList()
    {
        $list = GoodsM::order('goods_id desc')->paginate(20);
        $this->assign('list', $list);
        return $this->fetch();
    }

    function addGoods()
    {
        $arrayList=array();
        $cateArr = Category::select()->toArray();

        foreach ($cateArr as $row) {
            $arrayList[] = $row;
        }

        $tree = $this->getTree($arrayList, 0, 0);
        if($tree==null){
            $tree=array();
        }
        $this->assign('tree', $tree);
        return $this->fetch();
    }

    function goodsDel()
    {
        if (GoodsM::destroy(Request::param('id'))) {
            $this->redirect('goodsList');
        }
    }

    function addGoodsSave()
    {

        $files = $_FILES["pic"];
        $picArr = array();
        foreach ($files['name'] as $k => $fl) {
            //if($fl=='') continue;//如果上传图片是空，跳出本次循环。二改原样上传，方便修改头图顺序，前端调用时过滤。可以编个过滤公用方法。
            if ($files['size'][$k] > 1024 * 1024) {
                echo $fl . "大小超过512k,已过滤";
                continue;
            }

            $fileName = $fl;
            $tmpPath = $files['tmp_name'][$k];
            $ext = strrchr($fileName, '.');

            if ($ext == '') {//无后缀名文件过滤保存为空
                $picArr[] = '';
                continue;
            }

            if ($ext != '.jpg' and $ext != '.png' and $ext != '.gif' and $ext != '.jpeg') {
                echo $fl . "不是图片文件";
                continue;
            }

            $targetPath = "./uploads/";
            $saveFileName = md5($fileName) . rand(10000, 99999) . $ext;
            $saveDir = date("Ymd") . "/";
            if (!is_dir($targetPath . $saveDir)) {
                mkdir($targetPath . $saveDir);
            }
            $picArr[] = $saveDir . $saveFileName;
            move_uploaded_file($tmpPath, $targetPath . $saveDir . $saveFileName);

        }

        $data = Request::param();
        $data['pics'] = implode($picArr, ',');
        $goodm = new GoodsM();
        if ($goodm->save($data)) {
            $this->redirect('goodsList');
        } else {
            $this->error("添加商品失败", 'goodsList');
        }

    }

    public function goodsEdit()
    {
        $cateArr = Db::query("select * from lm_category");
        foreach ($cateArr as $row) {
            $arrayList[] = $row;
        }
        $tree = $this->getTree($arrayList, 0, 0);
        $this->assign('tree', $tree);

        $goods = GoodsM::with('cate')->find(Request::param('id'));
        $piclist = explode(',', $goods['pics']);

        for ($i = 0; $i <= 5 - count($piclist); $i++) {
            $piclist[] = "";
        }
        $this->assign('piclist', $piclist);
        $this->assign('goods', $goods);
        return $this->fetch();
    }

    /**商品修改功能
     * @return void
     */
    public function editGoodsSave()
    {
        $data = Request::param();
        $goods = GoodsM::find(Request::param('goods_id'));
        $picArr = explode(",", $goods->pics);
        for ($i = 0; $i <= 5 - count($picArr); $i++) {
            $picArr[] = "";
        }

        $files = $_FILES["pic"];

        foreach ($files['name'] as $k => $fl) {
            //这个表示删除这个图片。因为file的value只能是空串，所以加了给del域对应匹配标注是否删除。
            if ($data['del'][$k] == 1) {
                $picArr[$k] = "";
                continue;
            }
            if ($files['size'][$k] > 1024 * 1024) {
                echo $fl . "大小超过512k,已过滤";
                continue;
            }

            $fileName = $fl;
            $tmpPath = $files['tmp_name'][$k];
            $ext = strrchr($fileName, '.');

            if ($ext == '') {//无后缀名文件过滤保存为空
                $picArr[$k] = $picArr[$k];
                continue;
            }

            if ($ext != '.jpg' and $ext != '.png' and $ext != '.gif' and $ext != '.jpeg') {
                echo $fl . "不是图片文件";
                $picArr[$k] = $picArr[$k];
                continue;
            }

            $targetPath = "./uploads/";
            $saveFileName = md5($fileName) . rand(10000, 99999) . $ext;
            $saveDir = date("Ymd") . "/";
            if (!is_dir($targetPath . $saveDir)) {
                mkdir($targetPath . $saveDir);
            }
            $picArr[$k] = $saveDir . $saveFileName;
            move_uploaded_file($tmpPath, $targetPath . $saveDir . $saveFileName);

        }

        unset($data['del']);


        $data['pics'] = implode($picArr, ',');
        if ($goods->update($data)) {
            $this->success("修改商品成功", 'goodsList');
        } else {
            $this->error("修改商品失败", 'goodsList');
        }

    }

    /**
     * 商品下架
     * @return void
     */
    public function goodsOff()
    {
        $goods = GoodsM::find(Request::param('id'));
        $goods->goff = 0;
        if ($goods->save()) {
            $this->redirect('goodsList');
        }
    }

    /**
     * 商品上架
     * @return void
     */
    public function goodsUp()
    {
        $goods = GoodsM::find(Request::param('id'));
        $goods->goff = 1;
        if ($goods->save()) {
            $this->redirect('goodsList');
        }
    }

    public function categoryList()
    {
        $list = Category::select();
        $list = $this->getTree($list->toArray(), 0, 0);
        $this->assign('list', $list);
        return $this->fetch('goods/category_list');
    }

    public function categoryAdd()
    {
        $cateArr = Db::query("select * from lm_category");
        $arrayList=array();
        foreach ($cateArr as $row) {
            $arrayList[] = $row;
        }

        $tree = $this->getTree($arrayList, 0, 0);
        if($tree==null){
            $tree=array();
        }
        $this->assign('tree', $tree);
        return $this->fetch('');
    }

    public function categorySave()
    {
        $data = Request::param();
        $files=$_FILES['pic'];
        if($files['tmp_name']!=''){
            $pic=request()->file('pic');
            $info=$pic->move('./uploads/');
            $data['pic']="";
            if($info){
                echo $data['pic']=$info->getSaveName();
            }else{
                echo "上传图片异常";
            }
        }
        $category = new Category();
        if ($category->save($data)) {
            $this->redirect('goods/categoryList');
        } else {
            $this->error('添加分类失败', 'goods/categoryList');
        }
    }

    public function categoryEdit()
    {
        $cateArr = Db::query("select * from lm_category");
        foreach ($cateArr as $row) {
            $arrayList[] = $row;
        }

        $tree = $this->getTree($arrayList, 0, 0);

        $this->assign('tree', $tree);

        $cate = Category::find(Request::param('id'));
        $cate->pic=str_replace("\\","/",$cate->pic);
        $this->assign('cate', $cate);

        $pcate = Category::find($cate->pid);
        $this->assign('pcate', $pcate);

        return $this->fetch();
    }

    public function categoryEditUp()
    {
        $data = Request::param();
        $data['pic']="";
        $files = $_FILES["pic"];
        if($files['tmp_name']!=''){
            $pic=request()->file('pic');
            $info=$pic->move("./uploads/");
            if($info){
                echo $data['pic']=$info->getSaveName();
            }else{
                echo "上传图片异常";
            }
        }else{
            $c=Category::find(Request::param('id'));
            $data['pic']=$c['pic'];
        }
        if($data['del']==1){
            $data['pic']="";
        }
        if (Category::update($data)) {
            $this->redirect('categoryList');
        } else {
            $this->error("操作失败", 'categoryList');
        }
    }

    public function cateDel()
    {
        $ids=Request::param('id');
        $cateArr=Category::select();
        $cateArr=$cateArr->toArray();
        $cateArr=$this->getTree($cateArr,$ids,0);
        if($cateArr!=''){
            foreach ($cateArr as $r){
                $ids=$ids.",".$r['id'];
            }
        }

        GoodsM::where('cid','in',$ids)->delete();
        Category::destroy($ids);
        $this->redirect('categoryList');
    }


    function getTree($arr, $pid, $step)
    {
        global $tree;
        foreach ($arr as $key => $val) {
            if ($val['pid'] == $pid) {
                $flag = str_repeat("--", $step);
                $val['name'] = $flag . $val['name'];
                $val['step'] = $step;
                $tree[] = $val;
                $this->getTree($arr, $val['id'], $step + 1);
            }
        }

        return $tree;

    }


}